package br.senai.sc.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.senai.sc.controller.LoginController;
import br.senai.sc.entity.Usuario;

public class LoginFilter implements Filter {

	private static final String LOGIN = "/Bidman/index.xhtml";

	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;

		String url = request.getRequestURL().toString();

		if (!this.autorizacao((HttpServletRequest) req, url)
				&& precisaAutenticar(url)) {

			/*request.getRequestDispatcher(LOGIN).forward(req, res);*/
			response.sendRedirect(LOGIN);
		} else {
			/* Desativa o cache do browser */
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);

			/* Processa request e response */
			chain.doFilter(req, res);

		}
	}

	public void destroy() {
	}

	/* Metodo que verifica se existe um funcionário logado na sessão */
	private boolean autorizacao(HttpServletRequest req, String url) {
		boolean retorno = false;
		HttpSession session = req.getSession(false);
		if (session != null) {
			LoginController login = (LoginController) session
					.getAttribute("loginController");
			if (login != null) {
				Boolean logado = login.getLogado();
				Usuario usuario = login.getUsuario();
				if (logado != null && logado == true && usuario != null
						&& usuario.getId() != null) {
					if (usuario.getPerfil() == 2) {						
						retorno = !(url.matches(".*pages/edital.*")
								|| url.matches(".*pages/produto.*")
								|| url.matches(".*pages/user/listar.*"));	
					} else {
						retorno = true;
					}
				}
			}
		}
		return retorno;
	}

	/*
	 * Não autentica as páginas de javascript, css e imagens Necessário para
	 * carregas os estilos do primefaces na página de login
	 */
	private boolean precisaAutenticar(String url) {
		return !url.endsWith(".css") && !url.endsWith(".js")
				&& !url.endsWith(".jpg") && !url.endsWith(".gif")
				&& !url.endsWith(".png") && !url.endsWith("index.xhtml")
				&& !url.endsWith("detalheedital.xhtml")
				&& !url.contains("ln=images")
				&& !url.contains("Bidman/images/")
				&& !url.contains("Bidman/javax.faces.resource/")
				&& !url.contains("/pages/user/fornecedor.xhtml");
	}

}
